package com.myz.service.ribbon.config;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author maoyz
 */
@Configuration
@AutoConfigureBefore(RibbonClientConfiguration.class)
public class RibbonConfig {

    @Value("${ribbon.ConnectTimeout:5000}")
    private int connectTimeout;

    @Value("${ribbon.ReadTimeout:5000}")
    private int readTimeout;

    /**
     * 负载均衡策略
     * 默认 RoundRobinRule，配置随机机制 RandomRule
     *
     * @return
     */
    @Bean
    public IRule rule() {
        return new RoundRobinRule();
    }

    /**
     * RestTemplate 默认使用的是 SimpleClientHttpRequestFactory
     * 使用负载均衡器 @LoadBalanced -> LoadBalancerAutoConfiguration
     *
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setReadTimeout(readTimeout);
        httpRequestFactory.setConnectTimeout(connectTimeout);
        return new RestTemplate(httpRequestFactory);
    }

}
